#!/bin/bash
# 设置默认日志文件路径（可通过参数传入）
read -p "请输入日志存在的目录: " LOG_FILE_PATH
echo "Installing Amazon CloudWatch Agent..."
sudo yum install -y amazon-cloudwatch-agent
CONFIG_FILE="/home/ec2-user/amazon-cloudwatch-agent.json"
echo "Creating CloudWatch Agent configuration at $CONFIG_FILE..."

cat <<EOF | sudo tee $CONFIG_FILE
{
  "logs": {
    "logs_collected": {
      "files": {
        "collect_list": [
          {
            "file_path": "$LOG_FILE_PATH",
            "log_group_name": "ec2_cloudwatch_logs",
            "log_stream_name": "{instance_id}"
          }
        ]
      }
    }
  }
}
EOF
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/home/ec2-user/amazon-cloudwatch-agent.json -s
echo "Starting CloudWatch Agent..."
sudo systemctl start amazon-cloudwatch-agent
echo "Verifying CloudWatch Agent status..."
sudo systemctl status amazon-cloudwatch-agent
echo "enable reboot"
sudo systemctl enable amazon-cloudwatch-agent
echo "CloudWatch Agent setup complete!"
